<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.key" placeholder="高级查询"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" round v-on:click="queryData" class="el-icon-zoom-in">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" round @click="handleAdd" class="el-icon-plus">新增</el-button>
          <el-button type="danger"  round @click="batchRemove" :disabled="this.sels.length===0" class="el-icon-delete">批量删除</el-button>
          <el-button type="primary"  round @click="uploadVisible = true"  class="el-icon-plus">导入员工</el-button>
          <el-button type="success"  round @click="downloadTemplate"  class="el-icon-minus">导出员工</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="100" >
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100" >
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" >
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" >
      </el-table-column>
      <el-table-column prop="headImage" label="头像图片" width="185" >
      </el-table-column>
      <el-table-column prop="department.name" label="部门" width="100" >
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button type="success" plain size="small"  @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" plain size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" plain size="small" @click="setRole(scope.$index, scope.row)">角色</el-button>
        </template>
      </el-table-column>
		</el-table>
		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
      <!--
        el-pagination 表示分页
        @size-change 每页跳数变化时候会触发的方法
        @current-change 当前页数改变的时候
        :current-page 绑定当前页的数据
        :page-sizes="[100, 200]  每页多少调的选择
        :page-size="100"  每页的条数
        :total="400" 总数
      -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="search.currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      style="float:right"
      >
      </el-pagination>
		</el-col>
    <!--导入界面-->
    <el-dialog title="导入文件" :visible.sync="uploadVisible" :close-on-click-modal="true">
      <el-upload class="upload-demo" drag action="/api/employee/upload" :on-success="uploadSuccess"
                 :before-upload="beforeAvatarUpload" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过10mb</div>
      </el-upload>
    </el-dialog>
    <!--错误数据界面-->
    <el-dialog title="无效数据" top="5vh" :visible.sync="failVisible" :close-on-click-modal="true" width="70%">
      <el-table :data="failList" highlight-current-row border style="width: 100%;">
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120" sortable></el-table-column>
        <el-table-column prop="email" label="邮箱" width="240"></el-table-column>
        <el-table-column prop="age" label="年龄" width="160" sortable></el-table-column>
        <el-table-column prop="headImage" label="头像" sortable></el-table-column>
        <el-table-column prop="department.name" label="所属部门" width="160" sortable></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="download">导出</el-button>
      </div>
    </el-dialog>
		<!--新增/修改界面-->
		<el-dialog title="新增/修改界面" :visible.sync ="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px"  ref="addForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="密码" prop="password">
        <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader v-model="saveForm.department.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false" plain >取消</el-button>
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
			</div>
		</el-dialog>
    <!--授予角色界面-->
    <el-dialog title="授予角色" :visible.sync="setRoleFormVisible" :close-on-click-modal="false">
      <el-form :model="setRoleForm" label-width="160px" >
        <el-form-item label="员工姓名" prop="username" >
          <el-input v-model="setRoleForm.employee.username" disabled auto-complete="off" id="username"></el-input>
        </el-form-item>
        <el-form-item label="授予角色">
          <el-tree
              :data="data"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              :props="props"
              style="margin-top: 10px">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="setRoleSubmit" >提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
	export default {
		data() {
			return {
        failList: [],
        failVisible: false,
        uploadVisible:false,
        props :{
          children: 'children',
          label: 'name'
        },
        setRoleForm:{
          employee:{
            id : "",
            username : "",
          },
          roles:[],
        },
        data:[],
        setRoleFormVisible : false,
        deptTree: [],
        employees: [],
        search: {
					key: '',
          pageSize: 5,
          currentPage: 1
				},
				pageInfo:{
          data: [] ,
          total: 0,
        },
				listLoading: false,
				sels: [], //列表选中列
        saveFormVisible : false,
        saveForm : {
          id : null,
          username:"",
          password:"",
          age:"",
          email:"",
          headImage:"",
          department:{
            id :null,
            name: "",
            path: "",
            parent: {
              id:null,
              name:""
            }
          }
        }
			}
		},
		methods: {
		  // 导入Excel
      uploadSuccess(response) {
        // console.log(response)
        if (response.success) {
          if (response.data.length) {
            this.failVisible = true;
            this.uploadVisible = false;
            this.failList = response.data;
            console.log(this.failList);
          }
          this.$message.success(response.msg)
          this.getEmployees();

        } else {
          this.$message.error(response.msg)
        }
      },
      beforeAvatarUpload(file) {
        const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        const isSizeLt10M = file.size / 1024 / 1024 < 10;
        if (!isXlsx) {
          this.$message.error('上传头像图片只能是 xlsx 格式!');
        }
        if (!isSizeLt10M) {
          this.$message.error('上传大小不能超过 10MB!');
        }
        return isXlsx && isSizeLt10M;
      },
      //员工部门
      getManager(){
        this.$http.get("/department")
            .then(res=>{
              res = res.data
              if (res.success){
                this.employees = res.data;
                console.log(this.employees);
              }
            })
            .catch(res=>{ })
      },
      // 导出Excel数据
      downloadTemplate() {
        this.$http.post("/employee/download", this.search, {
          responseType: 'blob'})
            .then(response => {
              console.log("开始导出");
              const fileUrl = URL.createObjectURL(new Blob([response.data]));
              console.log(response.data);
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = "员工数据" + Date.now() + ".xlsx"; // 设置下载的文件名
              link.click(); // 模拟点击事件，触发文件下载
              this.getEmployees();
            })
            .catch(error => this.$message.error('网络异常: ' + error));
      },
      // 导出错误信息
      download() {
        this.$http.post("/employee/download1", this.failList, {responseType: 'blob'})
            .then(response => {
              const fileUrl = URL.createObjectURL(new Blob([response.data]));
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = "员工数据" + Date.now() + ".xlsx"; // 设置下载的文件名
              link.click(); // 模拟点击事件，触发文件下载
              this.failVisible = false;
            })
            .catch(error => this.$message.error('网络异常: ' + error));
      },
      // 获取所有角色
      getRoles(){
        this.$http.get("/role")
            .then(res=>{
              res=res.data
              if(res.success){
                this.data = res.data;
                this.queryRoleByEmpId();
              }
            })
            .catch(res=>{})
      },
      // 打开授予员工角色页面
      setRole(index,row){
        this.setRoleFormVisible = true;
        // console.log(row)
        this.setRoleForm.employee=JSON.parse(JSON.stringify(row))
        this.getRoles();
      },
      // 授予角色方法
      setRoleSubmit(){
        this.setRoleForm.roles = this.$refs.tree.getCheckedNodes()

        this.$http.post("/employee/empSetRole",this.setRoleForm)
            .then(res=>{
              if(res.data.success){
                this.$message({type:"success",message:"授予角色成功"});
              }else{
                this.$message.error("授予角色失败"+res.data.msg)
              }
              this.setRoleFormVisible = false;

            })
            .catch(res=>{})
      },
      // 查员工角色
      queryRoleByEmpId(){
        this.$http.post("/employee/empRole/"+this.setRoleForm.employee.id)
            .then(res=>{
              res=res.data
              if(res.success){
                var ids = res.data
                console.log(ids);
                this.$refs.tree.setCheckedKeys(ids);
              }
            })
            .catch(res=>{})
      },
      //获取员工的更据部门的员工上级部门树方法
      getDeptTree(){
        //发送请求
        this.$http.get("/employee/deptTree")
            .then(res=>{
              res = res.data;
              if(res.success){
                this.deptTree = res.data;
              }
            })
            .catch(res=>{})
      },
		  //点击新增方法
      handleAdd(){
        this.saveFormVisible = true;
        //清空数据
        this.saveForm = {
          id : null,
          username:"",
          password:"",
          age:"",
          email:"",
          headImage:"",
          department:{
            id :null,
            name: "",
            path: "",
            parent: {
              id :null,
              name: ""
            },
          }
        }
        this.getEmployees();
        this.getDeptTree();
      },
		  //点击查询方法
      queryData(){
        this.search.currentPage = 1;
        this.getEmployees();
      },
      //每页跳数变化时候会触发的方法
      handleSizeChange(value){
        this.search.pageSize = value;
        this.search.currentPage = 1;
        this.getEmployees();
      },
			handleCurrentChange(val) {
				//val 当前页的页数
        this.search.currentPage = val;
        this.getEmployees();
			},
			//获取用户列表
			getEmployees() {
				this.listLoading = true;
				this.$http.post("/employee",this.search)
        .then(res=>{
          this.listLoading = false;
          res = res.data
          if (res.success){
            this.pageInfo = res.data;
          }
        })
        .catch(res=>{})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/employee/"+row.id)
					.then(res=>{
            res = res.data;
            console.log(res);
            this.listLoading = false;
            if (res.success){
              this.$message({type:"success",message:"删除成功"})
            }else {
              this.$message.error("删除失败"+res.msg);
            }
            this.search.currentPage = 1;
            this.getEmployees();
          })
          .catch(res=>{

          })

				}).catch(() => {

				});
			},
			//显示新增/修改界面
			handleSave: function (index,row) {
				this.saveFormVisible = true;
        this.saveForm = JSON.parse(JSON.stringify(row)); //回显数据
        var split = row.department.path.split("/");
        var data = [];
        for (let i = 1; i < split.length; i++) {
          data.push(Number.parseInt(split[i]));
        }
        this.saveForm.department.parent = data;
        if (row.department.parent){
            this.saveForm.department.parent = {
              id:null,
              name: ""
          }
        }
        //调用上级部门树的方法
        this.getDeptTree();
        this.getEmployees(); //刷新页面
			},
			//新增/修改
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              //拷贝数据
              let para = Object.assign({}, this.saveForm);
              var parent = para.department.parent;
              //将所属部门的层级进行判断，最后将数组最后一位
              if (parent.length >= 0){
                if (parent.length==0){
                  para.department={id:null,name:""}
                }else{
                  para.department={id:parent[parent.length-1],name:""}
                }
              }
              // 发送请求
              this.$http.put("/employee",para).then(res=>{
                this.saveFormVisible= false
                this.$message({type:"success",message:"保存成功"});
                this.getEmployees()
              }).catch(res=>{})
            });
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          // 发送请求
          this.$http.patch("/employee",ids)
              .then(res=>{
                res = res.data;
                console.log(res);
                this.listLoading = false;
                if (res.success){
                  this.$message({type:"success",message:"删除成功"})
                }else {
                  this.$message.error("删除失败"+res.msg);
                }
                this.search.currentPage = 1;
                this.getEmployees(); //刷新页面
              })
              .catch(res=>{

              })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getEmployees();

		}
	}
</script>

<style scoped>

</style>